import dayjs from 'dayjs'

// pages/videoplay/video.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

/*
 * 列表数据
 * 不能放在page构造方法后面
 */
let commentList = [
    {
        id: 1,
        user_id: 1,
        user_name: "小五",
        user_avatar: "https://cdn.uviewui.com/uview/template/SmilingDog.jpg",
        user_content:
            "女性多少岁会绝经？",
        user_date: "2021-12-25 18:58",
        allReply: 4,
        user_like_num: 33,
        user_is_like: true,
        isMyComment: true,
        isLoading: false,
        user_reply_list: [
            {
                user_reply_id: 20,
                user_reply_name: "宋医师",
                user_reply_content:
                    "医师的答复~",
                user_reply_avatar:
                    "https://cdn.uviewui.com/uview/template/niannian.jpg",
                user_reply_is_like: true,
                user_reply_like_num: 1,
                user_reply_date: "2023-06-01 12:00",
                pid: 1,
                user_isMyComment: true,
            },
            {
                user_reply_id: 21,
                user_reply_name: "陈医师",
                user_reply_content:
                    "医师的进一步答复~",
                user_reply_avatar:
                    "https://cdn.uviewui.com/uview/template/niannian.jpg",
                user_reply_is_like: false,
                user_reply_like_num: 0,
                user_reply_date: "2023-06-01 19:00",
                to_user_name: "宋医师",
                to_user_id: 20,
                pid: 1,
                user_isMyComment: true,
            },
        ],
    },
    {
        id: 2,
        user_id: 2,
        user_name: "小六",
        user_date: "2021-01-25 13:58",
        user_content:
            "用户提问二",
        allReply: 0,
        user_like_num: 11,
        user_is_like: false,
        user_avatar: "https://cdn.uviewui.com/uview/template/niannian.jpg",
        isLoading: false,
        user_reply_list: [],
        isMyComment: true,
    },
    {
        id: 3,
        user_id: 3,
        user_name: "小七",
        user_date: "2021-03-25 13:58",
        user_content:
            "用户提问三",
        user_like_num: 21,
        user_is_like: false,
        allReply: 3,
        user_avatar: "https://cdn.uviewui.com/uview/template/niannian.jpg",
        isLoading: false,
        isMyComment: true,
        user_reply_list: [
            {
                user_reply_id: 20,
                user_reply_name: "陈医师",
                user_reply_content:
                    "对于这个问题，我认为关键在于更全面地考虑各种因素。我们可以尝试从不同的角度来看待，以确保我们的讨论更加全面和深刻。",
                user_reply_avatar:
                    "https://cdn.uviewui.com/uview/template/niannian.jpg",
                user_reply_is_like: true,
                user_reply_like_num: 1,
                user_reply_date: "2023-06-01 12:00",
                pid: 3,
                user_isMyComment: true,
            },
            {
                user_reply_id: 21,
                user_reply_name: "宋医师",
                user_reply_content:
                    "你的观点让我回想起了一个相似的情境。当时我面临了类似的抉择，经历了一些挑战。我想分享一下那段经历，看看是否对我们的讨论有所启发。",
                user_reply_avatar:
                    "https://cdn.uviewui.com/uview/template/niannian.jpg",
                user_reply_is_like: false,
                user_reply_like_num: 0,
                user_reply_date: "2023-06-01 19:00",
                to_user_name: "陈医师",
                to_user_id: 20,
                pid: 3,
                user_isMyComment: true,
            },
        ],
    },
];

// commentList = []
// 模拟当前用户信息
const userInfo = {
    id: 999,
    name: 'luffyGo',
    url: App.globalData?.fulluserInfo?.avatar,
    contentStr: '',
    isLike: false,
    likeNum: 0,
    date: "2024-02-22 12:00",
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "视频详情"
        },

        video: {},
        newHeight: 'auto;',

        // 用户信息 是否为会员
        userInfo: {},
        isVip: false,

        // 评论列表数据
        commentList: [],

        page: 1,
        limit: 5,

        // 提问加载标识
        loading: false,
        // 是否有更多数据标识 
        noMoredata: false,

        askInpVisible: false,
        placeholder: '提出疑问，医师稍后会给您回复噢~',
        themeColor: '#1DBFB6',
        inputVal: '',
        comtIptFocusStatus: false,

        positionStauts: 'relative',
        keyboardheight: 0,

        // 是否匿名 0/1 默认为0非匿名
        is_anonymity: 0,


        // 是否为医师 默认为否 不展示回复字样
        isDoctor: false,

        // 视频源ID
        videoID: -1,

        // 升级会员模态框
        confirmBtn: { content: '去升级', variant: 'base' },

        showVipModal: false,

        // 提问添加图片原始数组
        originFiles: [],
        // 每行上传图片列数以及图片的宽度和高度
        gridConfig: {
            column: 4,
            width: 160,
            height: 160,
        },

        // 行高
        autosize: {
            maxHeight: 60,
            minHeight: 20,
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let { id, url, text, poster, videoStr } = options
        console.log(id, url, text, poster, videoStr);
        if (videoStr) {
            let video = JSON.parse(videoStr)
            console.log("video", video);
            this.setData({
                video: video,
                videoID: video.id,

                userInfo: App.globalData.userInfo,
                isVip: App.globalData.isVip,
                VipGrade: App.globalData.VipGrade,
            })
        } else {
            // console.log("哈哈哈哈哈", url, text, poster, id);
            // console.log(userInfo);
            this.setData({
                ['video.name']: text,
                ['video.url']: url,
                ['video.poster']: poster,
                ['video.id']: id,
                videoID: id,

                userInfo: App.globalData.userInfo,
                isVip: App.globalData.isVip,
                VipGrade: App.globalData.VipGrade,

            })
        }

        if (this.data.videoID == -1 || !this.data.videoID) {
            util.showToast("视频加载有误，请重新加载")
            wx.navigateBack({
                delta: 1
            });

        }

        let userInfo = this.data.userInfo
        let hasFullAvatar = Reflect.has(userInfo, "fullAvatar")
        if (!hasFullAvatar) {
            App.simpleLogin().then(() => {
                this.setData({
                    userInfo: App.globalData.userInfo
                })
            }).catch((err) => {
                console.log(err);
            })

        }

        util.showLoading('视频加载中')
        this.getQuestionlist(this.data.page, this.data.limit)
        // 利用防抖函数初始化输入框内容修改方法
        this.writeContent = this.debounce(300, (content) => {
            // console.log('我在这', content, this);
            this.setData({
                inputVal: content
            })
        })

        // 鉴别医师身份，决定是否展示回复字样
        let eid = this.data.userInfo.uid
        let doctorList = [4, 121, 120]
        let isDoctor = doctorList.some(item => item == eid)
        if (isDoctor) {
            this.setData({
                isDoctor: true
            })
        }

        // 生成分享sid
        this.build_sid()
        this.queryWmemberInfo()

        // 用户通过分享链接进入才会有的操作
        // 用于积累分享积分、绑定分销上下级关系（nobind=0）
        let { sid, nobind } = options
        if (sid) {
            this.getsid = sid
            this.nobind = nobind

            console.log("sid-nobind", sid, nobind);
            this.sendShareInfo()
        }

    },

    // 调用分享接口
    async sendShareInfo() {
        let shareRes

        console.log('this.data.uid-detail', this.data.uid);

        // 使用uid方式 无法绑定分销上下级关系
        // 已登录
        // if (this.data.uid) {
        //     shareRes = await request.post(api.sendShare, { uid: this.data.uid, sid: this.getsid })
        //     console.log('shareRes 11111', shareRes);
        // }
        // // 未登录 调用wx.login接口
        // else {
        wx.login({
            success: async res => {
                if (res.code) {
                    let params = {
                        code: res.code,
                        sid: this.getsid,
                        nobind: this.nobind
                    }
                    shareRes = await request.post(api.sendShare, params)
                    console.log('shareRes 22222', shareRes);
                }
            },
            fail: err => {
                console.log(err);
            }
        })
        // }
        console.log('shareRes', shareRes);
    },


    // 查询提现人员详细信息
    async queryWmemberInfo() {
        let wDetail = await request.post(api.queryWmemberInfo, { uid: this.data.userInfo.uid })
        console.log("提现人详情", wDetail);

        // 提现人员详情不显示在页面 无需记录在data中
        this.wDetail = wDetail ? wDetail : {
            allin_moblie: "",
            true_name: ""
        }
    },

    // 拼接分享sid并保存到data
    async build_sid() {
        let id = this.data.videoID
        let uid = this.data.uid
        if (!uid) {
            await App.gologin()
            // 朋友圈直接查看页面，无法使用wx.login，所以登录会失败。因此需要这个提示
            if (!App.globalData.uid) {
                util.showToast('前往小程序查看更多视频咨询')
                return
            }
            let sid = App.globalData.uid + 'a' + id + 'a14'
            this.sharesid = sid
        } else {
            let sid = App.globalData.uid + 'a' + id + 'a14'
            this.sharesid = sid
        }
        // console.log('build_sid', this.data.sharesid);
    },
    // 图片上传相关方法
    handleSuccess(e) {
        const { files } = e.detail;
        this.setData({
            originFiles: files,
        });
    },
    handleRemove(e) {
        const { index } = e.detail;
        const { originFiles } = this.data;
        originFiles.splice(index, 1);
        this.setData({
            originFiles,
        });
    },
    handleClick(e) {
        console.log(e.detail.file);
    },
    // 将临时图片上传到小程序后台服务器
    async uploadTemPhoto(photoUrl) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: api.upload_photo, // 已切换韦总接口真实地址
                filePath: photoUrl, // 临时地址，并非真正图片的路径
                name: 'imgFile',
                success(res) {
                    // console.log(res);
                    const data = JSON.parse(res.data)
                    // console.log(data);
                    resolve(data)
                },
                fail(err) {
                    resolve(err)
                }
            })
        })
    },

    // 防抖函数
    debounce(delay, callback) {
        let timer;
        return function (content) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                clearTimeout(timer);
                callback.apply(this, [content])
            }, delay);
        };
    },

    /**
         * 输入框内容改变 => 更新v-model
         */
    onChangeIput(e) {
        let content = e.detail.value
        this.writeContent(content)
    },

    // 以下两个方法解决键盘部分遮挡输入框事件
    // input组件 keyboardheightchange事件失效，不用
    // focus事件亦可以获取键盘高度，但需blur事件配合复原
    // adjust- position="{{false}}"聚焦禁止上推动屏幕
    keyboardheightchange(e) {
        console.log("keyboardheightchange", e?.detail?.height);
        let keyboardheight = e?.detail?.height || 0
        // console.log(keyboardheight);

        // this.setData({
        //     positionStauts: keyboardheight == 0 ? 'relative' : 'fixed', // fixed
        //     keyboardheight: keyboardheight == 0 ? 0 : 320,

        // })
        // setTimeout(() => {
        //     this.setData({
        //         keyboardheight: keyboardheight,
        //     })
        // }, 100);
    },

    handleBlur() {
        // this.setData({
        //     positionStauts: 'relative',
        //     keyboardheight: 0,
        // })
    },

    // 设置评论空状态
    setEmptyStatus() {
        this.setData({
            commentList: []
        })
    },

    setWidthHeight(e) {
        util.hideLoading()

        let that = this
        let query = wx.createSelectorQuery()
        let outterbox = query.select(".outterbox")
        outterbox.fields({
            rect: true,
            dataset: true,
            size: true,
            scrollOffset: true,
            properties: ['scrollX', 'scrollY'],
            computedStyle: ['margin', 'backgroundColor'],
            context: true,
        }, function (res) {
            let oo = e.detail.height / e.detail.width
            let newHeight = oo * res.width
            // console.log('获取outterbox', res);
            // console.log(e.detail);
            // console.log('newHeight', newHeight);
            that.setData(
                {
                    newHeight: `${newHeight}px;`
                }
            )
        }).exec()

        // let {}
    },

    // 弹出提问框
    showAskInput() {
        // 如果提问有会员限制，调用该方法
        // let showflag = this.showVipModal()

        // 无提问限制则使用默认 true
        let showflag = true
        if (showflag) {
            this.setData({
                askInpVisible: true,
                comtIptFocusStatus: false
            })
        } else return

    },

    showVipModal() {
        let isVip = this.data.isVip
        if (isVip) return true
        this.setData({
            showVipModal: true
        })
        return false
    },

    confirmDialog() {
        wx.navigateTo({
            url: '/vip/buy_vip?chosenid=2',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });
        this.setData({
            showVipModal: false
        })
    },

    cancelDialog() {
        this.setData({
            showVipModal: false
        })
    },

    /**
         * 弹框change事件
         */
    onChangePop(e) {
        let flag = e.detail.visible
        // console.log(flag);
        this.setData({
            comtIptFocusStatus: flag,
            askInpVisible: flag
        })
    },

    // 视频提问
    async askQuestion() {
        let inputVal = this.data.inputVal
        if (inputVal.length == 0) return util.showToast('输入不能为空哦~')

        let result = await this.sendQuestion()
        // console.log('result2222', result);
        if (result.code !== 0) return util.showFail('提交失败请重试')

        // 已经提交成功 清除上传图片的数组
        this.setData({
            originFiles: []
        })
        util.showFail('已提交，请耐心等待审核')

        let userInfo = this.data.userInfo
        // console.log(userInfo);
        let newparams = {
            id: -1,
            user_id: userInfo.uid,
            user_name: userInfo.nickName,
            user_avatar: userInfo.fullAvatar,
            user_content: inputVal,
            user_date: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            allReply: 0,
            user_like_num: 0,
            user_is_like: false,
            isMyComment: true,
            isLoading: false,
            user_reply_list: []
        }

        // let commentList = this.data.commentList
        // commentList.unshift(newparams)
        // console.log(commentList);
        this.setData({
            // commentList: [newparams], // 提交问题后 取消立即显示在问题列表
            inputVal: '',
            askInpVisible: false,
            comtIptFocusStatus: false
        })
        // console.log('this.data.commentList', this.data.commentList);
    },

    loadError(e) {
        util.showToast('视频播放错误')
    },

    // 点击加载更多提问
    async clickLoadMore() {
        let page = this.data.page
        let limit = this.data.limit
        this.setData({
            loading: true
        })
        await this.getQuestionlist(++page, limit)
        this.setData({
            page: page,
            loading: false
        })
        wx.pageScrollTo({
            selector: ".positionPoint",
            offsetTop: -100
        })
    },

    // 获取本视频下的提问
    async getQuestionlist(page, limit) {
        console.log("this.data.videoID", this.data.videoID);
        let params = {
            source_id: this.data.videoID,
            page,
            limit
        }
        let list = await request.post(api.questionlist, params)
        if (!Array.isArray(list)) return console.log('暂无更多用户问题')

        if (list.length == 0) {
            this.setData({
                noMoredata: true
            })
            return
        }
        for (let index = 0; index < list.length; index++) {
            const qid = list[index]['id'];
            list[index]['page'] = 1
            let dataAll = await this.getAnswerlist(qid, list[index]['page'])
            list[index]['allReply'] = dataAll.count
            list[index]['isMyComment'] = list[index]['uid'] == this.data.userInfo.uid ? true : false;
            list[index]['user_reply_list'] = dataAll.data ? dataAll.data : []
            list[index]['noMore'] = list[index]['user_reply_list'].length >= list[index]['allReply'] ? true : false;

            list[index]['page']++
        }
        let formatList = this.formatMethod(list)

        let oldList = this.data.commentList
        let newList = oldList.concat(formatList)
        this.setData({
            commentList: newList
        })
    },

    // 将问题数组数据库字段格式化为页面渲染字段
    formatMethod(questionlist) {
        if (!Array.isArray(questionlist)) {
            console.log('请求数据非数组类型 渲染有误')
            return []
        }
        console.log(this.data.userInfo.uid);
        let newlist = questionlist.map(item => {
            // 去除数组空串元素
            let temArr = item.likes.split(',')
            let newArr = temArr.filter(function (element) {
                return element !== undefined && element !== '';
            });
            return {
                id: item.id,
                user_id: item.uid,
                user_name: item.nickname,
                user_avatar: item.avatar,
                user_content: item.content,
                // 13位的时间戳，其精度是毫秒(ms)；
                // 10位的时间戳，其精度是秒(s)；服务器返回的是10位
                // user_date: dayjs(item.create_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
                user_date: item.create_time,
                allReply: item.allReply,
                user_like_num: newArr.length,
                user_is_like: newArr.includes(`${this.data.userInfo.uid}`),
                isMyComment: item.isMyComment,
                isLoading: false,
                user_reply_list: item.user_reply_list,
                page: item.page,
                noMore: item.noMore,
                img_array: item.img_array
            }
        });
        // console.log(newlist);
        return newlist
    },

    // 请求问题下的回答
    async getAnswerlist(qid, page = 1, limit = 1) {
        if (!qid) return console.log('qid丢失');
        let params = {
            qid,
            page,
            limit
        }
        let dataRes = await request.postall(api.answerlist, params)
        let newlist = this.formatAnswer(dataRes.data)
        return {
            count: dataRes.count,
            data: newlist
        }
    },

    // 将回答数组数据库字段格式化为页面渲染字段
    formatAnswer(answerlist) {
        if (!Array.isArray(answerlist)) {
            console.log('请求数据非数组类型 渲染有误')
            return []
        }
        let newlist = answerlist.map(item => {
            // 去除数组空串元素
            let temArr = item.likes.split(',')
            let newArr = temArr.filter(function (element) {
                return element !== undefined && element !== '';
            });
            return {
                // 此处不用回答的用户ID 为了省事不改组件内部，将回复ID赋给reply_id
                // user_reply_id: item.eid,
                user_reply_id: item.id,

                user_reply_name: item.nickname,
                user_reply_content: item.content,
                user_reply_avatar: item.avatar,
                user_reply_is_like: newArr.includes(`${this.data.userInfo.uid}`),
                user_reply_like_num: newArr.length,
                // user_reply_date: dayjs(item.create_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
                user_reply_date: item.create_time,

                pid: item.qid,
                user_isMyComment: item.eid == this.data.userInfo.uid ? true : false,
            }
        });
        return newlist
    },

    // 用户提问方法
    // 发送请求提交用户提问
    async sendQuestion() {
        // 上传图片拿到存放地址
        let pathARR = this.data.originFiles
        let imgUrl = []
        for (let i = 0; i < pathARR.length; i++) {
            let path = pathARR[i].url
            let uploadRes = await this.uploadTemPhoto(path)
            if (uploadRes.code == 0) {
                imgUrl.push(uploadRes.data.img)
            }
        }
        let imgsStr = imgUrl.length == 0 ? '' : imgUrl.join(',')
        console.log("imgsStr", imgsStr);

        let params = {
            uid: this.data.userInfo.uid,
            content: this.data.inputVal,
            is_anonymity: this.data.is_anonymity,
            source_id: this.data.videoID,
            imgs_str: imgsStr
        }
        // return console.log(params);
        util.showLoading('提交中')
        let Res = await request.postall(api.questionadd, params)
        util.hideLoading()
        return Res
    },

    // 此方法暂时不用
    // 医师回复方法
    // 发送请求回复用户提问
    async sendAnswer(qid) {
        let eid = this.data.userInfo.uid
        let params = {
            eid,
            qid,
            content: this.data.inputVal,
            is_anonymity: this.data.is_anonymity,
        }
        util.showLoading('提交中')
        let Res = await request.postall(api.answeradd, params)
        console.log('result3333', Res);

        util.hideLoading()
        return Res
    },



    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let isVip = App.globalData.isVip

        // 不一致则重置用户会员标识
        if (this.data.isVip != isVip) {
            this.setData({
                isVip: App.globalData.isVip
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        let mobile = this.wDetail.allin_moblie
        let truename = this.wDetail.true_name
        let VipGrade = this.data.VipGrade
        let sid = this.sharesid

        // 记录分享次数
        request.postall(api.wxacodeshare, { uid: this.data.userInfo.uid, sid: sid }).then((res) => {
            console.log(res);
        })

        let videoStr = JSON.stringify(this.data.video) // 将视频信息对象转字符串

        let nobind = 1 // 正常不绑定关系
        // 视频暂时不做分销关系绑定
        // if (mobile.length == 11 && truename != "" && VipGrade >= 1) {
        //     nobind = 0 // 如果是分销员 则置零 绑定关系
        // }

        let share_path = `/pages/videoplay/video`;
        let sharePath = `/pages/home/home?share=${share_path}&sid=${sid}&videoStr=${videoStr}&nobind=${nobind}`

        // console.log(share_path, sharePath1);
        let shareObj = {
            title: this.data.video.name,
            path: sharePath,
            imageUrl: this.data.video?.poster,
            success: function (res) {
                if (res.errMsg == 'shareAppMessage:ok') {
                    util.showToast('分享成功');
                }
            },
            fail: function (err) {
                console.log(err);
                util.showToast('分享失败');
            },
        };
        // console.log(sid, mobile);
        console.log('shareObj', shareObj);
        return shareObj;
    },

    // wx.showShareMenu
    // 无法使用async 会导致分享参数异常
    // 分享到朋友圈只能携带参数，无法决定跳转的路径
    onShareTimeline() {
        let mobile = this.wDetail.allin_moblie
        let truename = this.wDetail.true_name
        let VipGrade = this.data.VipGrade
        let sid = this.sharesid

        // 记录分享次数
        request.postall(api.wxacodeshare, { uid: this.data.userInfo.uid, sid: sid }).then((res) => {
            console.log(res);
        })

        // 如果是分销员 这置零绑定关系
        let nobind = 1
        // if (mobile.length == 11 && truename != "" && VipGrade >= 1) {
        //     nobind = 0 // 视频暂时不做分销关系绑定
        // }

        let videoStr = JSON.stringify(this.data.video)

        // 不需要路径
        // let healthPath = `/pages/good/detail`;
        // let homePath = `/pages/home/home`
        // let query2 = `&videoStr=${videoStr}`
        let query = `sid=${sid}&videoStr=${videoStr}&nobind=${nobind}`


        let shareObj = {
            title: this.data.video.name,
            query: query,
            imageUrl: this.data.video.poster,
            success: function (res) {
                if (res.errMsg == 'shareAppMessage:ok') {
                    util.showToast('分享成功');
                }
            },
            fail: function (err) {
                console.log(err);
                util.showToast('分享失败');
            },
        };
        console.log(shareObj);
        return shareObj
    },

    // 以下为评论组件相关方法

    inputValue: '',
    // 子组件输入框的输入内容回调
    updateValue(e) {
        let inputValue = e.detail.detail.value
        // console.log('输入框', inputValue);
        this.inputValue = inputValue
    },

    /**
     * 发送评论事件
     * @param data {index: number, index_s: number, row: {一级评论的信息}, row_s: { 点击当前回复的信息} }
     * @param callback
     */
    async sendComment(e) {
        let data = e.detail.data
        let callback = e.detail.callback
        // 给一级评论回复时，row_s 为空对象 {}
        // console.log(data, callback); // 输出： {index: 0, index_s: 0, row: {…}, row_s: {…}}
        if (this.inputValue.length == 0) return util.showToast('输入不能为空哦~')

        let answerData = {
            content: this.inputValue,
            eid: this.data.userInfo.uid,
            qid: data.row.id,
            is_anonymity: data.row.is_anonymity ? 1 : 0
        }
        // return
        util.showLoading('回复中')
        let res = await request.postall(api.answeradd, answerData)
        console.log('result3333', res);

        util.hideLoading()
        if (res.code != 0) return console.log('回复失败', res);
        const params = { ...userInfo, id: res.data, date: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'), contentStr: this.inputValue }

        // 判断是否有回复的人，有的话，就是回复的回复，没有就是回复的一级评论
        if (data?.row_s?.id) {
            params.to_user_id = data.row_s.id
            params.to_user_name = data.row_s.name
        }

        // 评论接口发送成功后，把当前评论的信息传给 callback(新的评论信息，接口返回) 用于更新评论列表
        callback(params)
        this.inputValue = ''

    },

    /**
     * 获取更多评论
     * @param data {index: number, row: {一级评论的信息}}
     * @param callback 调用获取更多回复接口成功后，调用该方法更新回复列表，会自动关闭加载动画
     */
    async getMore(e) {
        let data = e.detail.data
        let callback = e.detail.callback
        console.log(data.row.noMore);
        console.log(data.row.hideList);
        if (data.row.noMore) return callback(data.row.hideList)
        let res = await this.getAnswerlist(data.row.id, data.row.page)
        console.log(res);
        callback(res.data)
        // 调用 获取更多评论接口，成功后调用 callback(【新的评论信息，接口返回，可是对象】) 用于更新评论列表
        // console.log(data, 'data');
        // setTimeout(() => {
        //     callback([
        //         {
        //             user_reply_name: "医师三",
        //             user_reply_id: 20,
        //             user_isMyComment: true,
        //             user_reply_content:
        //                 "这是待加载的回复一",
        //             user_reply_avatar: "https://cdn.uviewui.com/uview/template/SmilingDog.jpg",
        //             user_reply_is_like: false,
        //             user_reply_like_num: 33,
        //             pid: data.row.id,
        //             user_reply_date: "2023-06-01 12:00",
        //             to_user_id: '',
        //             to_user_name: '',
        //         },
        //         // {
        //         //     user_reply_name: "医师四",
        //         //     user_reply_id: 21,
        //         //     user_isMyComment: true,
        //         //     pid: data.row.id,
        //         //     user_reply_content:
        //         //         "这是待加载的回复二",
        //         //     user_reply_avatar: "https://cdn.uviewui.com/uview/template/SmilingDog.jpg",
        //         //     user_reply_is_like: false,
        //         //     user_reply_like_num: 33,
        //         //     user_reply_date: "2023-06-01 12:00",
        //         //     to_user_id: '',
        //         //     to_user_name: '',
        //         // },
        //     ]);
        // }, 1000);
    },

    /**
     * 点赞事件
     * @param data {index: number, j: number}  index 一级评论的索引 j 回复的索引
     * @param callback  调用点赞接口成功后，调用该方法更新点赞状态
     * j 是给二级回复点赞，给一级评论点赞时，j 为undefined
     */
    async getLike(e) {
        let data = e.detail.data
        let callback = e.detail.callback

        //  此处可以发送请求，改变数据库的点赞状态
        let { index, j } = data
        // console.log(index, j,);
        let reqPath = '', params = {}
        if (j.id || j.id == 0) {
            let like = j.like
            reqPath = like ? api.answercancellike : api.answergivelike
            params.id = j.id
            params.uid = this.data.userInfo.uid
        } else {
            let like = index.like
            reqPath = like ? api.questioncancellike : api.questiongivelike
            params.id = index.id
            params.uid = this.data.userInfo.uid
        }

        let reqResult = await request.postall(reqPath, params)
        // console.log('reqResult', reqResult);
        if (reqResult.code !== 0) return util.showToast(reqResult.msg)

        // 点赞成功后调用该方法 更新点赞状态
        callback();
    },

    /**
     * 删除评论
     */
    async remove(e) {
        let data = e.detail.data
        let callback = e.detail.callback

        // 调用删除接口
        console.log(data);
        let answerid = data.row_s?.id
        let delPath = ''
        let params = {
            ids: ''
        }
        if (typeof answerid == "number") {
            // console.log('删除回复');
            delPath = api.answerdelete
            params.ids = data.row_s.id
        } else if (typeof answerid == "undefined") {
            // console.log('删除提问');
            delPath = api.questiondelete
            params.ids = data.row.id
        } else {
            console.log('未知');
        }
        let delRes = await request.postall(delPath, params)
        console.log("delRes", delRes);
        if (delRes.code == 0) {
            util.showToast('删除成功')
            // 调用删除接口成功后，调用 callback() 用于更新评论列表
            callback()
            return
        } else {
            return util.showToast('删除失败' + delRes.msg)
        }


    },
})